/**
 * 
 */
package it.unical.canonaco.rende.igpe.game.cbv.guilayer.gamemanagermenu.menucomponent;

import it.unical.canonaco.rende.igpe.game.cbv.guilayer.components.GUIGenericPawn;
import it.unical.canonaco.rende.igpe.game.cbv.guilayer.components.ImageProvider;
import it.unical.canonaco.rende.igpe.game.cbv.guilayer.components.OverallGUILayoutFactory;
import it.unical.canonaco.rende.igpe.game.cbv.guilayer.gamemanagermenu.ClickMouseMapListener;
import it.unical.canonaco.rende.igpe.game.cbv.guilayer.gamemanagermenu.MapAreaPanel;
import it.unical.canonaco.rende.igpe.game.cbv.guilayer.guievents.CharacterClickEvent;
import it.unical.canonaco.rende.igpe.game.cbv.guilayer.guievents.ClickedMapCellEvent;
import it.unical.canonaco.rende.igpe.game.cbv.guilayer.guievents.GraphicEvent;
import it.unical.canonaco.rende.igpe.game.cbv.guilayer.guievents.GraphicEventListener;
import it.unical.canonaco.rende.igpe.game.cbv.guilayer.guievents.GraphicEventManager;
import it.unical.canonaco.rende.igpe.game.cbv.guilayer.sprites.SpriteSheetCache;
import it.unical.canonaco.rende.igpe.game.cbv.guilayer.sprites.key.AvatarFrameKey;
import it.unical.canonaco.rende.igpe.game.cbv.guilayer.sprites.key.PawnSheetKey;
import it.unical.canonaco.rende.igpe.game.cbv.logiclayer.engine.GameManager;
import it.unical.canonaco.rende.igpe.game.cbv.logiclayer.engine.actions.ActionCoordinateInfo;
import it.unical.canonaco.rende.igpe.game.cbv.logiclayer.engine.actions.ActionMediator;
import it.unical.canonaco.rende.igpe.game.cbv.logiclayer.engine.actions.AddCharacterInfo;
import it.unical.canonaco.rende.igpe.game.cbv.logiclayer.engine.actions.GenericActionInfo;
import it.unical.canonaco.rende.igpe.game.cbv.logiclayer.engine.actions.RemoveStartingPointAction;
import it.unical.canonaco.rende.igpe.game.cbv.logiclayer.engine.actions.StartingPointAction;
import it.unical.canonaco.rende.igpe.game.cbv.logiclayer.engine.component.pawn.Character;
import it.unical.canonaco.rende.igpe.game.cbv.logiclayer.engine.component.pawn.stats.AbilityStats;
import it.unical.canonaco.rende.igpe.game.cbv.logiclayer.engine.component.pawn.stats.Stats;
import it.unical.canonaco.rende.igpe.game.cbv.logiclayer.engine.component.player.SimplePlayer;
import it.unical.canonaco.rende.igpe.game.cbv.logiclayer.engine.events.EventListener;
import it.unical.canonaco.rende.igpe.game.cbv.logiclayer.engine.events.EventManager;
import it.unical.canonaco.rende.igpe.game.cbv.logiclayer.engine.events.GenericEvent;
import it.unical.canonaco.rende.igpe.game.cbv.logiclayer.engine.events.GenericEventManager;
import it.unical.canonaco.rende.igpe.game.cbv.logiclayer.engine.events.StartingPositionEvent;
import it.unical.canonaco.rende.igpe.game.cbv.logiclayer.engine.exceptions.InvalidFileException;

import java.awt.Color;
import java.awt.Component;
import java.awt.ComponentOrientation;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.plaf.basic.BasicProgressBarUI;

/**
 * @author Massimo Canonaco
 *
 */
class LeftMenuPanel016 extends JPanel implements EventListener, MouseListener, GraphicEventListener
{
//		private static final String LEVEL_STRING = "Level";
//		private static final String ROLE_STRING = "Role";
		
//		private JLabel[] abilitesLabel;
		
		private JLabel characterRoleAvatar;
//		private JLabel level;
//		private JLabel role;
//
//		private JProgressBar experienceBar; 
		private JComboBox<GUIGenericPawn> characterListMenu;
		private SpriteSheetCache imgProvider;
		private JButton removeButton;
		private JButton addButton;
		
		private DisplayLeftMenuPanel016 characterInfoPanel;
		
		private ActionMediator actionMediator;
		private Point clicked;
		private PawnSheetKey avatarKey;
		
		/** */
		private GameManager gameManager;
		
		public LeftMenuPanel016(final GameManager gm, SpriteSheetCache imgCache, final Map<String,String> settings, final List<Character> characters, final it.unical.canonaco.rende.igpe.game.cbv.logiclayer.engine.component.world.Map arena)
		{
			super();
			gameManager = gm;
			this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
			final String ROLES_IMAGES_PATH = "cbvapps"+File.separator+"textures"+File.separator+"rolesimgs"+File.separator,
					PROGESSBAR_INCOMPLETE_COLOR = "pm.leftmenu.progressbar.incompletecolor",
					PROGRESSBAR_COMPLETE_COLOR = "pm.leftmenu.progressbar.completecolor",
					PROGESSBAR_TEXT_COLOR = "pm.leftmenu.progressbar.text.color",
					PROGESSBAR_TEXT_SIZE = "pm.leftmenu.progressbar.text.size";
			imgProvider = imgCache;
//			final ImageProvider irp = new ImageProvider(ROLES_IMAGES_PATH);
			JPanel selectionPanel = new JPanel();
			characterInfoPanel = new DisplayLeftMenuPanel016(Stats.TOTAL_STATISTICS, characters.get(0).getStats().getAbilities().size(), settings);
			OverallGUILayoutFactory guiFactory = OverallGUILayoutFactory.getInstance();
			final Dimension buttonDimension = new Dimension(Integer.parseInt(settings.get("pm.leftmenu.button.width")), Integer.parseInt(settings.get("pm.leftmenu.button.height"))),
					characterListMenuDimension = new Dimension(Integer.parseInt(settings.get("pm.leftmenu.dsp.list.width")), Integer.parseInt(settings.get("pm.leftmenu.dsp.list.height")));
			int textSize = Integer.parseInt((String)settings.get("pm.leftmenu.button.text.size"));
			setBackground(guiFactory.getParsedColor(settings.get("pm.leftmenu.dsp.backcolor")));
//			actionMediator = gm.getMatchManager().getClientPlayer().getActions(); // !critico
			clicked = new Point();
			EventManager.getInstance().addListener(this, new StartingPositionEvent());
			GraphicEventManager.getInstance().addListener(this, CharacterClickEvent.class);
			GraphicEventManager.getInstance().addListener(this, ClickedMapCellEvent.class);
			characterListMenu = new JComboBox<GUIGenericPawn>();
			characterListMenu.setPreferredSize(characterListMenuDimension);
			characterListMenu.setSize(characterListMenuDimension);
			characterListMenu.setMaximumSize(characterListMenuDimension);
//			GUIGenericPawn temp = null; //!critico
//			for(Character toAdd : characters)
//			{
//				temp = new GUIGenericPawn();
//				temp.setLogicPart(toAdd);
////				temp.setAvatar(irp.getAvatar(toAdd.getStats().getName()));
//				characterListMenu.addItem(temp);
//			}
			
			avatarKey = new PawnSheetKey();
			avatarKey.setWhat(PawnSheetKey.FRAME_TYPE_AVATAR);
			avatarKey.setWho("");
			avatarKey.setWhen("");
			AvatarFrameKey afk = new AvatarFrameKey();
			afk.setKey(AvatarFrameKey.MINI_AVATAR);
			avatarKey.setFrameKey(afk);
			characterListMenu.addItemListener(characterInfoPanel);
			characterListMenu.addItemListener(new ItemListener() {

				@Override
				public void itemStateChanged(ItemEvent item) {
					if(item.getStateChange() == ItemEvent.SELECTED)
					{
						try {
							GUIGenericPawn selected = (GUIGenericPawn)item.getItem();
							avatarKey.setWho(selected.getLogicPart().getType());
							characterRoleAvatar.setIcon(new ImageIcon(imgProvider.getImage(avatarKey, 0, true)));
						} catch (InvalidFileException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}

					}


				}
			});

			selectionPanel.add(characterListMenu);
			characterRoleAvatar = new JLabel();
			characterRoleAvatar.setMinimumSize(new Dimension(50,50));
			selectionPanel.add(characterRoleAvatar);
			add(selectionPanel);
			selectionPanel.setOpaque(false);
			Dimension selectionDimension = new Dimension(523,55	);
			selectionPanel.setMinimumSize(selectionDimension);
			selectionPanel.setPreferredSize(selectionDimension);
			selectionPanel.setMaximumSize(selectionDimension);
//			add(characterListMenu);
			add(Box.createRigidArea(new Dimension(0, 22)));
			add(characterInfoPanel);
			
			removeButton = guiFactory.createButtonUniState(textSize, "Rimuovi", buttonDimension.width, buttonDimension.height, OverallGUILayoutFactory.BUTTON_STATE_ACTIVE);
			removeButton.setOpaque(false);
			removeButton.setMinimumSize(buttonDimension);
			removeButton.setPreferredSize(buttonDimension);
			characterListMenu.setSelectedIndex(-1);
//			characterListMenu.setSelectedIndex(0);
			characterListMenu.addActionListener(new ActionListener() 
			{
				@Override
				public void actionPerformed(ActionEvent arg0) 
				{
					GUIGenericPawn selected = (GUIGenericPawn)characterListMenu.getSelectedItem();
					buttonsAction(!selected.isaBoolean());
				}
			});
			
			
			
			addButton = guiFactory.createButtonUniState(textSize, "Aggiungi", buttonDimension.width, buttonDimension.height, OverallGUILayoutFactory.BUTTON_STATE_ACTIVE);
			addButton.setMinimumSize(buttonDimension);
			addButton.setPreferredSize(buttonDimension);
			addButton.addActionListener(new ActionListener() 
			{
				@Override
				public void actionPerformed(ActionEvent arg0) {
					GUIGenericPawn selected = (GUIGenericPawn)characterListMenu.getSelectedItem();
					actionMediator.clearInformations();
					actionMediator.setAction(StartingPointAction.GUID);
//					
					AddCharacterInfo aci = new AddCharacterInfo();
					aci.setCharacter((Character)selected.getLogicPart());
					
					ActionCoordinateInfo acii = new ActionCoordinateInfo(clicked.x, clicked.y);
					actionMediator.addActionInfo(aci);
					actionMediator.addActionInfo(acii);
//					System.out.println("here");
					selected.setaBoolean(actionMediator.playAction());
//					System.out.println("here2");
				}
			});

			removeButton.addActionListener(new ActionListener() {
				@Override
				public void actionPerformed(ActionEvent arg0) {
					
					GUIGenericPawn selected = (GUIGenericPawn)characterListMenu.getSelectedItem();
					AddCharacterInfo aci = new AddCharacterInfo();
					aci.setCharacter((Character)selected.getLogicPart());
					
					ActionCoordinateInfo acii = new ActionCoordinateInfo(selected.getLogicPart().getRow(), selected.getLogicPart().getColumn());
//					actionMediator.setAction(StartingPointAction.GUID);
					actionMediator.clearInformations();
					actionMediator.setAction(RemoveStartingPointAction.GUID);
					actionMediator.addActionInfo(aci);
					actionMediator.addActionInfo(acii);
					selected.setaBoolean(!actionMediator.playAction()); 
//					selected.setaBoolean(actionMediator.playAction()); 
				}
			});
			
			JPanel buttonPanel = new JPanel(new FlowLayout());
			buttonPanel.add(addButton);
			buttonPanel.add(removeButton);
			buttonPanel.setOpaque(false);
			add(buttonPanel);
			removeButton.setEnabled(false);
		}

		private void buttonsAction(boolean addBoolean)
		{
			addButton.setEnabled(addBoolean);
			removeButton.setEnabled(!addBoolean);
		}
		
		@Override
		public void notify(GenericEvent event) 
		{
			boolean result = true;

			if(event.getGUID() == StartingPositionEvent.GUID)
			{
				StartingPositionEvent spe = (StartingPositionEvent) event;
				GUIGenericPawn subject = (GUIGenericPawn)characterListMenu.getSelectedItem();
				if(subject.getLogicPart() == spe.getSubject())
				{
					if(spe.isAdd())
					{
						result = false;
					}
					else
					{
						result = true;
					}
				}
				else
				{
					if(subject.isaBoolean())
					{
						result = false;
					}
					else
					{
						result = true;
					}
				}
			}
			buttonsAction(result);
		}

		@Override
		public void mouseClicked(MouseEvent e) 
		{
//			MapAreaPanel.getMapAreaPoint(e.getX(), e.getY(), 50, clicked);
			
//			int size = characterListMenu.getItemCount();
//			boolean cicle = true;
//			for(int index = 0; index < size && cicle; index++)
//			{
//				if(characterListMenu.getItemAt(index).getLogicPart().getRow() == clicked.x 
//						&& characterListMenu.getItemAt(index).getLogicPart().getColumn() == clicked.y)
//				{
//					
//					characterListMenu.setSelectedIndex(index);
//					cicle = false;
//				}
//			}
		}

		@Override
		public void mouseEntered(MouseEvent arg0) {}

		@Override
		public void mouseExited(MouseEvent arg0) {}

		@Override
		public void mousePressed(MouseEvent arg0) {}

		@Override
		public void mouseReleased(MouseEvent arg0) {}

		@Override
		public void notify(GraphicEvent event) 
		{
			if(event instanceof CharacterClickEvent)
			{
				Character character = ((CharacterClickEvent) event).getClickedChar();
				
				int size = characterListMenu.getItemCount();
				boolean cicle = true;
				for(int index = 0; index < size && cicle; index++)
				{
					if(characterListMenu.getItemAt(index).getLogicPart().getRow() == character.getRow()
							&& characterListMenu.getItemAt(index).getLogicPart().getColumn() == character.getColumn())
					{
						characterListMenu.setSelectedIndex(index);
						cicle = false;
					}
				}
			}
			else if(event instanceof ClickedMapCellEvent)
			{
				ClickedMapCellEvent cellEvent = (ClickedMapCellEvent) event;
				clicked.x = cellEvent.getRow();
				clicked.y = cellEvent.getColumn();
			}
			
		}
		
		/** */
		public void someSetting()
		{
			actionMediator = gameManager.getMatchManager().getClientPlayer().getActions();

//			characterInfoPanel = new DisplayLeftMenuPanel016(Stats.TOTAL_STATISTICS, characters.get(0).getStats().getAbilities().length, settings);
			
			List<Character> characters = gameManager.getClientPlayer().getCharacters();
			GUIGenericPawn temp = null; //!critico
			for(Character toAdd : characters)
			{
				temp = new GUIGenericPawn();
				temp.setLogicPart(toAdd);
//				temp.setAvatar(irp.getAvatar(toAdd.getStats().getName()));
				characterListMenu.addItem(temp);
			}
			characterListMenu.setSelectedIndex(0);
		}
		
		/** */
		public void clear()
		{
			EventManager.getInstance().removeListener(this, new StartingPositionEvent());
		}
}
